package com.atwork.service.impl;

import com.atwork.model.normal.*;
import com.atwork.model.vo.ShiroUser;
import com.atwork.service.*;
import com.sun.deploy.panel.ITreeNode;
import com.sun.tools.jdi.EventSetImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @CreateBy: zhaojun
 * @CreateTime: 2018-08-04
 * @Desc: 系统权限用户模块
 */
@Service
public class ShiroUserServiceImpl implements ShiroUserService{
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysDeptService sysDeptService;
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private SysAclService sysAclService;
    @Autowired
    private SysResourceService sysResourceService;
    @Override
    public ShiroUser getShiroUser(String userName) {
        ShiroUser shiroUser = new ShiroUser();
        SysUser user = sysUserService.getUserByLoginName(userName);
        shiroUser.setLoginName(user.getLoginName());//设置登陆名
        shiroUser.setUserName(user.getUsername());//设置用户名
        shiroUser.setUserId(user.getId());//设置用户id
        /*设置部门*/
        List<SysDept> sysDepts = sysDeptService.getDeptByUserId(user.getId());
        shiroUser.setSysDept(sysDepts);
        /*设置角色*/
        List<SysRole> sysRoles = sysRoleService.getRoleByUserId(user.getId());
        shiroUser.setSysRole(sysRoles);
        /*设置权限*/
        Set<SysAcl> sysAcls = new HashSet<>();
        for(SysRole sysRole : sysRoles){
           List<SysAcl> sysAclsStr = sysAclService.getSysAclByRoleId(sysRole.getId());
           for(SysAcl sysAcl : sysAclsStr){
               sysAcls.add(sysAcl);
           }
        }
        shiroUser.setSysAcl(sysAcls);
        /*设置权限菜单*/
        Set<SysResource> sysResources = new HashSet<>();
        for(SysAcl sysAcl : sysAcls){
            if("1".equals(sysAcl.getType().toString())){
                SysResource sysResource = sysResourceService.getResourceById(sysAcl.getSysResourceId());
                if(sysResource != null){
                    sysResources.add(sysResource);
                }
            }
        }
        shiroUser.setSysResource(sysResources);
        /*设置权限菜单路径*/
        /*从权限模块中获取*/
        Set<String> sysResourceUrls = new HashSet<>();
        for(SysAcl sysAcl : sysAcls){
            sysResourceUrls.add(sysAcl.getUrl());
        }
        shiroUser.setResourceUrls(sysResourceUrls);
        /*从资源中获取*/
        /*for(SysResource sysResource : sysResources){
            sysResourceUrls.add(sysResource.getUrl());
        }*/
        /*设置角色名*/
        Set<String> sysRoleNames = new HashSet<>();
        for(SysRole sysRoleStr : sysRoles){
            sysRoleNames.add(sysRoleStr.getName());
        }
        shiroUser.setRoleListNames(sysRoleNames);
        return shiroUser;
    }
}
